<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="14">
        <el-form inline @submit.native.prevent="search">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.queryConditions"
              clearable
              placeholder="公告名/描述信息"
              prefix-icon="el-icon-search"
              size="medium"
            />
          </el-form-item>
          <el-form-item label="发布者">
            <el-select
              v-model="searchForm.account"
              clearable
              placeholder="全部"
              style="width: 150px"
              @change="publisherSelected"
            >
              <el-option
                v-for="item in publisher"
                :key="item.accountId"
                :value="item.accountId"
                :label="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button native-type="submit" size="medium" type="primary">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="10">
        <el-button
          type="danger"
          @click="deleteRecords(0)"
          icon="el-icon-remove-outline"
          class="btn"
        >
          批量删除
        </el-button>
        <el-button
          type="primary"
          @click="addAnnouncementDialog"
          icon="el-icon-circle-plus-outline"
          class="btn"
        >
          发布公告
        </el-button>
      </el-col>
    </el-row>
    <div>
      <el-table
        :data="list"
        border
        style="width: 100%"
        @selection-change="handleSelectChange"
        v-loading="announcementLoading"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column
          type="index"
          width="50"
          label="编号"
          fixed="left"
          align="center"
        />
        <el-table-column
          prop="ntitle"
          label="公告"
          width="200"
          align="center"
        />
        <el-table-column
          width="200"
          label="公告类型"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="primary">{{ scope.row.type === 1 ? "系统公告" : "招标公告" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="publisher.username"
          width="200"
          label="发布者"
          align="center"
        />
        <el-table-column
          prop="publisherRole.role"
          width="200"
          label="发布者身份"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.publisherRole.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          width="200"
          label="发布时间"
          align="center"
        />
        <el-table-column
          prop="modifier.username"
          width="200"
          label="修改者"
          align="center"
        />
        <el-table-column
          width="200"
          label="修改者身份"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="warning">{{ scope.row.modifierRole.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          width="200"
          label="修改时间"
          align="center"
        />
        <el-table-column
          prop="viewCounts"
          width="200"
          label="查阅量"
          align="center"
        />
        <el-table-column
          width="200"
          label="是否置顶"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="danger">{{
              scope.row.weight === 1 ? "置顶" : "不置顶"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template slot-scope="scope">
            <el-tooltip content="编辑公告信息" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
                @click="editAnnouncementDialog(scope.row)"
              />
            </el-tooltip>
            <el-tooltip content="删除公告" placement="top">
              <el-button
                el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="deleteRecords(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="paging.current"
        :page-sizes="paging.pageSizes"
        :page-size="paging.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <edit-dialog
      :index="index"
      :title="dialogTitle"
      :visible="editDialogVisible"
      :announcement-info="announcementInfo"
      :type="type"
      @cancel="cancel"
      @ok="ok"
    />
  </div>
</template>

<script>
import {
  listAnnouncement,
  updateAnnouncement,
  delAnnouncement,
  addAnnouncement,
  getAccountCanPublish,
} from "@/api/home.js";
import EditDialog from "./editDialog";
export default {
  name: "AnnouncementManage",
  components: { EditDialog },
  props: {
    type: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      searchForm: {
        queryConditions: "",
        account: "",
        type: this.type,
      },
      //departmentList: [],
      list: [],
      multipleSelection: [], //复选框选中的所有数据
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      publisher: [],
      announcementInfo: {},
      announcementLoading: false,
      editDialogVisible: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑
    };
  },
  created() {
    this.announcementLoading = true;
    this.getData();
    this.getAccountList();
  },
  methods: {
    async getAccountList() {
      const result = await getAccountCanPublish();
      this.publisher = result.data;
    },
    search() {
      this.paging.current = 1;
      this.announcementLoading = true;
      this.getData();
    },
    getData() {
      console.log("type:",this.type);
      const form = {
        ...this.searchForm,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      listAnnouncement(form)
        .then((res) => {
          if (res.data) {
            this.list = res.data.homeAnnouncements;
            // 返还每页显示的条数
            //this.paging.size = res.data.size;
            this.paging.total = res.data.totalCount;
            this.announcementLoading = false;
          }
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.announcementLoading = false;
        });
    },
    publisherSelected(val) {
      this.searchForm.account = val;
      this.search();
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    // 获取到选中的所有数据
    handleSelectChange(val) {
      this.multipleSelection = [];
      val.forEach((value) => {
        this.multipleSelection.push(value.id);
      });

      console.log(this.multipleSelection);
    },
    deleteRecords(val) {
      let ids = [];
      if (val === 0) {
        ids = this.multipleSelection;
        if (ids.length === 0) return;
      } else {
        ids.push(val.id);
      }
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const data = {
            ids: ids,
            accountId: this.$store.getters.accountId,
          };
          const result = await delAnnouncement(data);
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editAnnouncementDialog(row) {
      this.dialogTitle = "编辑公告信息";
      this.editDialogVisible = true;
      this.announcementInfo = this.extendCopy(row);
      this.index = 1;
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) {
        c[i] = p[i];
      }
      return c;
    },
    addAnnouncementDialog() {
      this.dialogTitle = "添加公告信息";
      this.editDialogVisible = true;
      this.index = 0;
    },
    cancel() {
      this.editDialogVisible = false;
      this.index = 1;
    },
    editAnnouncementInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑公告信息
          // console.log(val)
          const result = await updateAnnouncement(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addAnnouncement(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("添加成功");
            resolve(result);
          } else {
            this.$message.error("添加失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editAnnouncementInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(response);
    },
  },
};
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
</style>